import { PureComponent } from 'react';
import classNames from 'classnames';
import { View } from '@tarojs/components';
import './index.<%= css %>';

type ITabs = {
  key: string | number;
  title: string;
  number: number;
};

interface ITabProps {
  onChange?: (key: string | number, tab: any) => void;
  tabs: ITabs[];
  style: any;
  defaultActiveKey: string | number;
}

class Index extends PureComponent<ITabProps, any> {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: props.defaultActiveKey,
    };
  }

  changeTab = (activeKey, tab) => {
    if (this.state.activeKey === activeKey) return;
    const { onChange } = this.props;
    this.setState({
      activeKey,
    });
    onChange && onChange(activeKey, tab);
  };

  normalizeDot = (num) => (num > 99 ? `99+` : num);

  render() {
    const { activeKey } = this.state;
    const { tabs = [], style } = this.props;
    return (
      <View className="custom-component-tabs" style={style}>
        {tabs.map((tab) => {
          const { number, key, title } = tab;
          return (
            <View
              key={key}
              className={classNames(['tab', activeKey === key && 'active'])}
              onClick={() => this.changeTab(key, tab)}
            >
              <View className="tab-value">
                {title}
                {number > 0 && <View className="number-dot">{this.normalizeDot(number)}</View>}
              </View>
              <View className="line" />
            </View>
          );
        })}
      </View>
    );
  }
}
export default Index;
